package mybatis.binding;

import mybatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;

/**
 * sql查询动态代理增加处理，根据method类型判断是调用查那个查询方法
 */
public class MapperProxy implements InvocationHandler {

    private SqlSession session;

    public MapperProxy(SqlSession session) {
        super();
        this.session = session;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class<?> returnType = method.getReturnType();
        // 判断是否为集合类型
        if (Collection.class.isAssignableFrom(returnType)){
            return session.selectList(method.getDeclaringClass().getName()+"."+method.getName(),args==null ? null:args[0]);
        }else{
            return session.selectOne(method.getDeclaringClass().getName()+"."+method.getName(), args==null?null:args[0]);
        }
    }
}
